package icom.acm.util.redis;
/**
 * @author shench
 * redis数据库管理器
 */

import icom.acm.util.spring.SpringFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisDB {
	//****************单例一个连接池***************
	private static RedisDB db ;
    private ShardedJedisPool shardedJedisPool = null;
    private JedisPool jedisPool = null;
    private String password;
    
    public RedisDB(){
    }
    
    public RedisDB(ShardedJedisPool shardedJedisPool, JedisPool jedisPool, String password){
    	this.shardedJedisPool = shardedJedisPool;
    	this.jedisPool = jedisPool;
    	this.password = password;
    }
    
	 /**         
     * 获取连接池         
     * @return 数据源         
     */       
    public static synchronized RedisDB newInstance() {
    	try {
	    	SpringFactory sf = SpringFactory.newInstance();
	        if (db == null) 
	        	db = (RedisDB)sf.action(sf.bean, "RedisDB");
	        return db;
    	} catch (Exception ex){
    		ex.printStackTrace();return null;
    	}
    }        
    
    public ShardedJedis get_ShardedJedis(){
    	return shardedJedisPool.getResource();
    }
    public Jedis get_Jedis(){
    	Jedis jedis = jedisPool.getResource();
    	String flag =jedis.auth(password);
    	if (flag.equals("OK"))
    		return jedis;
    	return null;
    }
    /**
     * 关闭jedis的链接
     */
    public void close(ShardedJedis j){    	    	
    	shardedJedisPool.returnResource(j);   	
    }
    public void close(Jedis j){
    	jedisPool.returnBrokenResource(j);
    }
    /**
     * 摧毁连接池
     */
    public void destroy(){
    	shardedJedisPool.destroy();
    	
    }

	public ShardedJedisPool getShardedJedisPool() {
		return shardedJedisPool;
	}

	public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {
		this.shardedJedisPool = shardedJedisPool;
	}

	public JedisPool getJedisPool() {
		return jedisPool;
	}

	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}
      
}
